import { Component, createRef } from "inferno";
import Avatar from "./Avatar";
import IconListItem from "./ui/IconListItem";

class ChatDMItem extends Component {
  updateLastEvent = (event, room, ts) => {
    console.log("Room.timeline", this);
    if (room.roomId !== this.room.roomId) return;
    if (ts) return;
    console.log("[ChatDMItem]", room.roomId, " Got event: ", event.getType());
    if (event.getType() !== "m.room.message") return;
    let who = event.getSender();
    if (who === window.mClient.getUserId()) who = "You";
    this.setState({
      lastEvent: `${who}: ${event.getContent().body}`,
    });
  };

  updatePresence = (event, user) => {
    this.avatarRef.setState({ online: user.presence });
  };

  constructor(props) {
    super(props);
    const { avatar, room } = props;
    this.room = room;
    this.avatarRef = createRef();
    this.avatar = (
      <Avatar avatar={avatar} online="offline" ref={this.avatarRef} />
    );
    this.state = { lastEvent: null };
  }

  componentWillMount() {
    window.mClient.addListener("Room.timeline", this.updateLastEvent);
    window.mClient.addListener("User.presence", this.updatePresence);
  }

  componentWillUnmount() {
    window.mClient.removeListener("Room.timeline", this.updateLastEvent);
    window.mClient.removeListener("User.presence", this.updatePresence);
  }
  render() {
    return (
      <IconListItem
        icon={this.avatar}
        primary={this.room.name}
        secondary={this.state.lastEvent}
        key={this.props.isFocused}
        isFocused={this.props.isFocused}
      />
    );
  }
}

export default ChatDMItem;
